package com.example.socket_client_demo;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.uwantsoft.goeasy.client.goeasyclient.AndroidHelper;
import com.uwantsoft.goeasy.client.goeasyclient.GoEasy;
import com.uwantsoft.goeasy.client.goeasyclient.listener.GoEasyError;
import com.uwantsoft.goeasy.client.goeasyclient.listener.PublishListener;
import com.uwantsoft.goeasy.client.goeasyclient.listener.UnsubscribeListener;
import com.uwantsoft.goeasy.client.service.AbstractGoEasyReceiver;
import com.uwantsoft.goeasy.client.service.GoEasyService;
import de.greenrobot.event.EventBus;

public class MyActivity extends GoeasyActivity {
    private String TAG = ".MyActivity";
    EditText hostView;
    Button connectBtn;
    EditText appkeyView;
    EditText channelView;
    Button subscribeBtn;

    EditText sendMessageView;
    Button sendBtn;

    TextView sendMsgLabelView;
    TextView recvMsgLableView;

    Button unsubBtn;


    private static String currentServer;
    private static String currentAppkey;

    public MyActivity(){

    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
  try{
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      registerMessageReceiver();
      hostView = (EditText) findViewById(R.id.host);
      if(currentServer!=null){
          hostView.setText(currentServer);
      }

      connectBtn = (Button) findViewById(R.id.connectBtn);
      appkeyView = (EditText)findViewById(R.id.appkey);
      if(currentAppkey!=null){
          appkeyView.setText(currentAppkey);
      }

      channelView = (EditText) findViewById(R.id.channel);
      subscribeBtn = (Button) findViewById(R.id.subscribeBtn);
      unsubBtn = (Button)findViewById(R.id.unsubBtn);
      sendMessageView = (EditText) findViewById(R.id.sendmessage);
      sendBtn = (Button) findViewById(R.id.sendBtn);
      messageView = (EditText) findViewById(R.id.onmessage);

      sendMsgLabelView = (TextView) findViewById(R.id.sendMsgLabel);
      recvMsgLableView = (TextView) findViewById(R.id.recvMsgLabel);
      sendMsgLabelView.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
              MyActivity.this.runOnUiThread(new Runnable() {
                  public void run() {
                      sendMessageView.setText("");
                  }
              });
          }
      });
      recvMsgLableView.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
              MyActivity.this.runOnUiThread(new Runnable() {
                  public void run() {
                      messageView.setText("");
                  }
              });
          }
      });

      connectBtn.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
              Intent serviceIntent = new Intent(getApplicationContext(), GoEasyService.class);
              stopService(serviceIntent);
              String host = hostView.getText().toString();
              String appkey = appkeyView.getText().toString();
              if (host.trim().length() == 0 || appkey.trim().length() == 0) {
                  MyActivity.this.runOnUiThread(new Runnable() {
                      public void run() {
                          Toast.makeText(MyActivity.this, "Host and appkey is required", Toast.LENGTH_SHORT).show();
                      }
                  });
                  return;
              }
              AndroidHelper androidHelper = new AndroidHelper(getApplicationContext());
              androidHelper.remove("sid");
              GoEasyService.setHost(host);
              serviceIntent.putExtra("appkey", appkey);
              startService(serviceIntent);
              currentServer = host;
              currentAppkey = appkey;
          }
      });

      GoEasyService.setHost("192.168.31.218");
      final GoEasy goEasy = GoEasy.instance(getApplicationContext());
      goEasy.subscribe("demo_channel");
        sendBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                String toChannel = channelView.getText().toString();
                String sendMsg = sendMessageView.getText().toString();
                goEasy.publish(toChannel, sendMsg, new PublishListener() {
                    @Override
                    public void onSuccess() {
                        MyActivity.this.runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(MyActivity.this, "Publish successful.", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onFailed(final GoEasyError error) {
                        MyActivity.this.runOnUiThread(new Runnable() {
                            public void run() {
                                Toast.makeText(MyActivity.this, "Publish failed with code[" + error.getCode() + "] and message[" + error.getContent() + "]", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
            }
        });
      unsubBtn.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
              String toChannel = channelView.getText().toString();
              goEasy.unsubscribe(toChannel, new UnsubscribeListener() {
                  @Override
                  public void onSuccess() {
                      MyActivity.this.runOnUiThread(new Runnable() {
                          public void run() {
                              Toast.makeText(MyActivity.this, "Unsubscribe successfully.", Toast.LENGTH_SHORT).show();
                          }
                      });
                  }

                  @Override
                  public void onFailed(final GoEasyError error) {
                      MyActivity.this.runOnUiThread(new Runnable() {
                          public void run() {
                              Toast.makeText(MyActivity.this, "Unsubscribe failed with code[" + error.getCode() + "] and message[" + error.getContent() + "].", Toast.LENGTH_SHORT).show();
                          }
                      });
                  }
              });
          }
      });
      subscribeBtn.setOnClickListener(new View.OnClickListener() {
          public void onClick(View v) {
              String channel = channelView.getText().toString();
              goEasy.subscribe(channel);
          }
      });

  }catch (Throwable e){
      Log.w("GoEasy", e.getMessage());
  }
        Intent intent = getIntent();
        final String content_ = intent.getStringExtra("content");
        if(content_!=null && content_.trim().length() > 0){
            MyActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    messageView.append("Received message:" + content_ + "\n");
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unregisterReceiver(messageReceiver);
    }

    private MessageReceiver messageReceiver;
    public void registerMessageReceiver(){
        messageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(AbstractGoEasyReceiver.GOEASY_MESSAGE_ACTION);
        registerReceiver(messageReceiver, filter);
    }

    public class MessageReceiver extends AbstractGoEasyReceiver{

        @Override
        public void onSubscribeSuccess(Context context, String channel) {
            showMsg("Subscribe channel["+channel+"] successfully.");
        }

        @Override
        public void onSubscribeFailed(Context context, String channel,GoEasyError error) {
            showMsg("Subscribe channel["+channel+"] failed ["+error.getCode()+":"+error.getContent()+"].");
        }

        @Override
        public void onConnected(Context context) {
            showMsg("GoEasy connected.");
        }

        @Override
        public void onConnectFailed(Context context, GoEasyError error) {
            showMsg("GoEasy connect failed ["+error.getCode()+":"+error.getContent()+"].");
        }

        @Override
        public void onDisconnected(Context context) {
            showMsg("GoEasy disconnected.");
        }

        @Override
        public void onMessageReceived(Context context, String channel, String content) {
            showMsg("Received msg["+channel+"]:" + content);
        }

        private void showMsg(final String text){
            MyActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    messageView.append(text+"\n");
                }
            });
        }
    }

}
